<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="书名" prop="bookname">
        <el-input v-model="queryParams.bookname" placeholder="请输入书名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="作者" prop="authorname">
        <el-input v-model="queryParams.params.authorname" placeholder="作者" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['book:book:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['book:book:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['book:book:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['book:book:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bookList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="书名" align="center" prop="bookname" />
      <el-table-column label="导读" align="center" prop="description" />
      <el-table-column label="是否完结" align="center" prop="isfinish">
        <template slot-scope="scope">
          <span>{{ scope.row.isfinish? '已完结':'未完结' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="作者" align="center" prop="authorname" />
      <el-table-column label="类型" align="center" prop="typename" />
      <el-table-column label="购买次数" align="center" prop="buynums" />
      <el-table-column label="阅读次数" align="center" prop="readcount" />
      <el-table-column label="加入时间" align="center" prop="addtime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.addtime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="收藏次数" align="center" prop="tofavcount" />
      <el-table-column label="封面图片地址" align="center" prop="coverimg" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.coverimg" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="标签" align="center" prop="labelsList">
        <template slot-scope="scope">
          <span v-for="b in scope.row.labelsList">{{b.labname}} &nbsp;</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['book:book:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['book:book:remove']">删除</el-button>

          <el-button size="mini" type="text" icon="el-icon" @click="handleShowSec(scope.row)"
            v-hasPermi="['book:section:list']">查看章节</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改书籍对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="书名" prop="bookname">
          <el-input v-model="form.bookname" placeholder="请输入书名" />
        </el-form-item>
        <!-- 作者-->
        <el-form-item label="作者">
          <el-select v-model="form.authorid" placeholder="请选择" filterable :remote-method="getAuthorList">
            <el-option v-for="ah in authors" :key="ah.id" :label="ah.penname" :value="ah.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="form.typeid" placeholder="请选择" filterable>
            <el-option v-for="t in types" :key="t.id" :label="t.typename" :value="t.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="导读" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="封面图片地址" prop="coverimg">
          <image-upload v-model="form.coverimg" />
        </el-form-item>
        <el-form-item label="是否完结" prop="isfinish">
          <div>
            <el-radio :label="true" v-model="form.isfinish">已完结</el-radio>
            <el-radio :label="false" v-model="form.isfinish">未完结</el-radio>
          </div>
        </el-form-item>
        <el-form-item label="标签">
          <el-table :data="labels" @selection-change="handleBooklabelSelectionChange" ref="booklabel">
            <el-table-column type="selection" width="50" align="center" prop="id" />
            <!-- <el-table-column label="序号"  align="center" prop="id" width="50" /> -->
            <el-table-column label="标签" align="center" prop="labname" width="50" />
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listBook,
    getBook,
    delBook,
    addBook,
    updateBook
  } from "@/api/book/book";
  import {
    listAuthor
  } from "@/api/book/author";
  import {
    listLabel2
  } from "@/api/book/label";

  import { listType} from "@/api/book/type";

  export default {
    name: "Book",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 书籍表格数据
        bookList: [],

        //标签集合
        labels: [],
        checkedBooklabel: [],
        //作者数据!!!!!!!!!!!
        authors: [],
        //类型
        types: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          bookname: null,
          params:{}
        },
        queryBookParams: {
          pageNum: 1,
          pageSize: 40,
          penname: null,
        },

        // 表单参数
        form: {},
        // 表单校验
        rules: {
          bookname: [{
            required: true,
            message: "书名不能为空",
            trigger: "blur"
          }],
        }
      };
    },
    created() {
      this.getList();
      this.getTypes();
    },
    updated() {

      //选中已经选择的标签
      this.labels.forEach((sel) => {
        this.form.labelsList.forEach((row) => {
          ///console.log(sel.id,row.id);
          if (sel.id == row.id)
            this.$refs.booklabel.toggleRowSelection(sel, true);
        });
      });
    },
    methods: {
      /** 查询类型列表 */
      getTypes() {
        listType({pageSize:100,pageNum:1}).then(response => {
          this.types = response.rows;
        });
      },
      //下级选中
      /** 复选框选中数据 */
      handleBooklabelSelectionChange(selection) {
        //console.log(selection,">>>>>>")
        this.checkedBooklabel = [];
        //selection.map(item=>{this.checkedBooklabel.push({id:item.id})});
        selection.map(item => {
          this.checkedBooklabel.push(item)
        });
        //console.log("?????????????",JSON.stringify(this.checkedBooklabel));
      },

      //查询label
      getLabelsList(query) {
        listLabel2(null).then(response => {
          this.labels = response.data;
        });
      },

      /**查询作者**/
      // changeAu(event){
      //   console.log(event,">>>>");
      //   this.getAuthorList(null);
      // },
      getAuthorList(query) {
        this.queryBookParams.penname = query;
        //读取作者,作者不会超过10000
        listAuthor(this.queryBookParams).then(response => {
          this.authors = response.rows;
        });
      },
      /** 查询书籍列表 */
      getList() {
        this.loading = true;
        //alert(JSON.stringify(this.queryParams));

        listBook(this.queryParams).then(response => {
          this.bookList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          bookname: null,
          description: null,
          isfinish: null,
          authorid: null,
          typeid: null,
          buynums: null,
          readcount: null,
          addtime: null,
          tofavcount: null,
          coverimg: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加书籍";
        //this.getTypes();
        this.getAuthorList(null);
        this.getLabelsList(null);
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        //this.getTypes();
        this.getAuthorList(null);
        this.getLabelsList(null);


        const id = row.id || this.ids
        getBook(id).then(response => {
          this.form = response.data;
          //console.log("form",this.form);
          this.open = true;
          this.title = "修改书籍";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.form.labelsList = this.checkedBooklabel;

            if (this.form.id != null) {
              updateBook(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addBook(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除书籍编号为"' + ids + '"的数据项？').then(function() {
          return delBook(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 查看章节按钮操作 */
      handleShowSec(row) {
        const ids = row.id || this.ids;
        //console.log(ids,">>>>>>>>>>>>>>>>>>>>>>>>>>>")
        this.$router.push("/book/sectionb/listb/" + ids);
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('book/book/export', {
          ...this.queryParams
        }, `book_${new Date().getTime()}.xlsx`)
      }
    }
  };
</script>
